#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqLish.h"

void SLInit(SL* ps)
{
	assert(ps);
	SeqDataType* ptr = (SeqDataType*)malloc(sizeof(SeqDataType) * DEF_SIZE );
	if (ptr == NULL)
	{
		perror("malloc fail");
		return;
	}
	ps->data = ptr;
	ptr = NULL;

	ps->size = 0;
	ps->capacity = DEF_SIZE;
}

void SLCheckCapacity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capacity)
	{
		SeqDataType* ptr = (SeqDataType*)realloc(ps->data, sizeof(SeqDataType)* ps->capacity*2);
		if (ptr == NULL)
		{
			perror("realloc fail");
			return;
		}

		ps->data = ptr;
		ptr = NULL;
		ps->capacity *= 2;
	}
}

void SLDestroy(SL* ps)
{
	assert(ps);
	free(ps->data);
	ps->data = NULL;
	ps->capacity = ps->size = 0;
}

void SLPrint(SL* ps)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->data[i]);
	}
	printf("\n");
}

void SLPushBack(SL* ps, SeqDataType x)
{
	//assert(ps);
	//SLCheckCapacity(ps);
	//ps->data[ps->size] = x;
	//ps->size++;
	SLInsert(ps, ps->size, x);
}

void SLPopBack(SL* ps)
{
	//assert(ps);
	//assert(ps->size > 0);
	//ps->size--;
	SLErase(ps, ps->size-1);
}

void SLPushFront(SL* ps, SeqDataType x)
{
	//assert(ps);
	//SLCheckCapacity(ps);
	//int end = ps->size - 1;
	//while (end >= 0)
	//{
	//	ps->data[end+1] = ps->data[end];
	//	end--;
	//}
	//ps->data[0] = x;
	//ps->size++;
	SLInsert(ps, 0, x);
}

void SLPopFront(SL* ps)
{
	//assert(ps);
	//assert(ps->size > 0);
	//int begin = 1;
	//while (begin < ps->size)
	//{
	//	ps->data[begin - 1] = ps->data[begin];
	//	begin++;
	//}
	//ps->size--;

	SLErase(ps, 0);
}

void SLInsert(SL* ps, int pos, SeqDataType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	SLCheckCapacity(ps);
	int end = ps->size - 1;
	while (pos <= end)
	{
		ps->data[end + 1] = ps->data[end];
		end--;
	}
	ps->data[pos] = x;
	ps->size++;
}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	int end = pos + 1;
	while (end < ps->size)
	{
		ps->data[end - 1] = ps->data[end];
		end++;
	}
	ps->size--;
}

int SLFind(SL* ps, SeqDataType x)
{
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->data[i] == x)
		{
			return i;
		}
	}
	return -1;
}
